import {
	useUserStore
} from '@/store/userStore.js';

const userStore = useUserStore();
const env = wx.getAccountInfoSync().miniProgram.envVersion;

const Hosts = {
	develop: 'http://192.168.52.130:8081',
	trial: '',
	release: ''
}

const baseUrl = Hosts[env]

export {
	baseUrl
}

export function request(options) {

	let {
		method = 'GET',
		data = {},
		url,
		type,
	} = options

	let contentType = getContentType(type)

	let headers = {
		Accept: 'application/json, text/plain, */*',
		'Content-Type': contentType,
		'clientId': '43c2eede60722fc5e86965f646253e14',
	}

	// 处理 token
	let token = userStore.userToken ? userStore.userToken : uni.getStorageSync('userToken') ? uni.getStorageSync('userToken') : false;
	if (token) {
		headers['Authorization'] = 'Bearer ' + token;
	}

	// 发起请求
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url,
			method,
			header: headers,
			timeout: 20000, //超时时间20秒
			data,
			success(res) {
				// 登录过期
				if (res.data.code == 401) {
					uni.showToast({
						title: '登录超时，请重新登录',
						icon: 'none',
						duration: 2000
					})
					userStore.clearAll();
					userStore.$reset(); // 清空用户信息
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login/index'
						});
					}, 2000);
				}

				// 请求报错提示
				if (res.data.code != 200) {
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000
					})
				};

				resolve(res.data)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

// 获取请求头内容类型
function getContentType(type) {
	let contentType
	switch (type) {
		case 1:
			contentType = 'application/x-www-form-urlencoded'
			break
		case 2:
			contentType = 'multipart/form-data'
			break
		default:
			contentType = 'application/json;charset=UTF-8'
	}
	return contentType
}